package com.eflying.user.web.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eflying.user.bean.User;
import com.eflying.user.exception.UserException;
import com.eflying.user.service.UserService;

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;

/**
 * 用户模块web(控制层)层
 */
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserService();
	/**
	 * 修改密码功能
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updatePassword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 1.封装表单数据到user中
		 * 2.session中获取uid
		 * 3.封装异常信息，转发到pwd.jsp
		 * 4.保存成功信息到msg，转发到msg.jsp
		 * 
		 */
		User formUser = CommonUtils.toBean(request.getParameterMap(), User.class);
		User user = (User) request.getSession().getAttribute("sessionUser");
		if(user==null){
			request.setAttribute("msg", "您还未登陆，请登陆后重试！");
			return "f:/jsps/user/login.jsp";
		}
		try {
			userService.updatePassword(user.getUid(), formUser.getLoginpass(), formUser.getNewloginpass());
			request.setAttribute("msg", "密码修改成功！");
			request.setAttribute("code", "success");
			return "f:/jsps/msg.jsp";
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("user", formUser);
			return "f:/jsps/user/pwd.jsp";
		}
		
	}

	/**
	 * 注册方法
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String regist(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*
		 * 1.封装表单数据
		 */
		User formUser = CommonUtils.toBean(request.getParameterMap(), User.class);
		/*
		 * 2.校验,如果校验失败，则返回regist.jsp页面，并通知错误信息
		 */
		Map<String, String> errors = userService.validateRegist(formUser, request.getSession());
		if (errors.size() > 0) {

			request.setAttribute("form", formUser);
			request.setAttribute("errors", errors);
			return "f:/jsps/user/regist.jsp";
		}
		/*
		 * 3.使用service层完成
		 */
		userService.regist(formUser);
		/*
		 * 4.成功返回页面，msg.jsp
		 */
		request.setAttribute("code", "success");
		request.setAttribute("msg", "注册成功，请马上去邮箱激活！");
		return "f:/jsps/msg.jsp";

	}

	/**
	 * 用户名是否注册校验
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateLoginname(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String loginname = request.getParameter("loginname");
		boolean b = userService.ajaxValidateLoginname(loginname);
		response.getWriter().print(b);
		return null;
	}

	/**
	 * email是否已经注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateEmail(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String email = request.getParameter("email");
		boolean b = userService.ajaxValidateEmail(email);
		response.getWriter().print(b);
		return null;
	}

	/**
	 * 验证码是否正确
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String ajaxValidateVerifyCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String verifyCode = request.getParameter("verifyCode");

		String vcode = (String) request.getSession().getAttribute("vCode");
		boolean b = verifyCode.equalsIgnoreCase(vcode);
		response.getWriter().print(b);
		return null;
	}

	/**
	 * 邮件激活码
	 * 1.获取激活码
	 * 2.调用service中的激活方法，得到异常信息，保存进requset，转发到msg.jsp
	 * 3.激活成功，转发到msg.jsp中
	 * 
	 */

	public String activation(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String activationCode = request.getParameter("activationCode");
		try {
			userService.checkActivationCode(activationCode);
			request.setAttribute("code", "success");
			request.setAttribute("msg", "恭喜，激活成功，请马上登陆！");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("code", "error");
		}
		return "f:/jsps/msg.jsp";
	}

	/**
	 * 登陆功能
	 */
	public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1.封装表单数据到User(以后前端可以选择用AnglarJS在scope中将Model的数据以json对象形式传过来，
		 * 这样可以分离前后端的耦合性) 
		 * 2.校验表单数据 
		 * 3.使用service层查询得到User对象 
		 * 4.查看用户是否存在，存在
		 * >再次验证是否激活
		 * >激活：存入User到session中，保存用户名称到cookie中(注意编码)，并且forward到index.jsp 
		 * >未激活：
		 * 保存用户数据：便于回显，增加用户体验 forward到login.jsp，报错 不存在 
		 * >保存错误信息：用户名或者密码错误
		 * >保存用户数据：便于回显，增加用户体验 >forward到login.jsp
		 */
		// 封装表单数据
		User formUser = CommonUtils.toBean(request.getParameterMap(), User.class);

		// 2.校验,如果校验失败，则返回regist.jsp页面，并通知错误信息
		Map<String, String> errors = userService.validateLogin(formUser, request.getSession());
		if (errors.size() > 0) {

			request.setAttribute("form", formUser);
			request.setAttribute("errors", errors);
			return "f:/jsps/user/login.jsp";
		}

		// 调用service的login方法
		User user = userService.login(formUser);

		// 校验登陆
		if (user == null) {
			request.setAttribute("msg", "用户名或者密码错误！");
			request.setAttribute("user", formUser);
			return "f:/jsps/user/login.jsp";
		} else {
			if (!user.isStatus()) {
				request.setAttribute("msg", "您还没有激活！");
				request.setAttribute("user", formUser);
				return "f:/jsps/user/login.jsp";
			} else {
				request.getSession().setAttribute("sessionUser", user);
				Cookie cookie = new Cookie("loginname", URLEncoder.encode(user.getLoginname(), "UTF-8"));
				cookie.setMaxAge(60 * 60 * 24 * 10);
				response.addCookie(cookie);
				return "r:/index.jsp";
			}
		}
	}
	/**
	 * 退出功能
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String quit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		return "r:/jsps/user/login.jsp";
	}

}
